// https://www.lintcode.com/problem/closest-binary-search-tree-value/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the given BST
     * @param target: the given target
     * @return: the value in the BST that is closest to the target
     */
    public int closestValue(TreeNode root, double target) {
        // write your code here
        if (root.val > target) {
            if (root.left != null) {
                int val = closestValue(root.left, target);
                return (Math.abs(root.val - target) > Math.abs(val - target)) ? val : root.val;
            }
        } else if (root.val < target) {
            if (root.right != null) {
                int val = closestValue(root.right, target);
                return (Math.abs(root.val - target) > Math.abs(val - target)) ? val : root.val;
            }
        }
        return root.val;
    }
}